-- Sync time with some servers from the NTP pool and print the result, or that it failed

function set_ntp(x)
    if x>20 then
        print('Error: set_ntp timeout')
        return 0
    end
    
    if wifi.sta.status()<5 then
        print('Set NTP failed, wifi status='..wifi.sta.status()..', wait 2s ...')
        n = x+1
        tmr.alarm(1, 3000, 0, function()
            set_ntp(n)
        end)
    else
        print('Setting NTP ...')
        sntp.sync({ 'cn.pool.ntp.org', 
                    'ntp.aliyun.com',
                    'ntp1.aliyun.com',
                    'ntp2.aliyun.com',
                    'ntp3.aliyun.com',
                    'ntp4.aliyun.com',
                    'ntp5.aliyun.com',
                    'ntp6.aliyun.com',
                    'ntp7.aliyun.com',
                    'ntp.ntsc.ac.cn'},
          function(sec, usec, server, info)
            --print('sync', sec, usec, server)
            rtctime.set(sec+28800, usec)    --28800 东八区
            tm = rtctime.epoch2cal(rtctime.get())
            print(string.format("date : %04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
          end,
          function()
           print('NTP set failed!')
          end
        )
    end
end

set_ntp(0)
